package com.beverages.orders.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beverages.orders.client.CustomerIndividualClient;
import com.beverages.orders.client.MerchantHolderClient;
import com.beverages.orders.entity.Orders;
import com.beverages.orders.entity.dto.OrdersDTO;
import com.beverages.orders.service.IOrdersService;
import com.beverages.orders.common.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/customer/orders")
public class OrdersController {

    @Resource
    private IOrdersService ordersService;

    @Autowired
    private CustomerIndividualClient customerIndividualClient;

    @Autowired
    private MerchantHolderClient merchantHolderClient;

    @ApiOperation(
            value = "分页查看订单",
            notes = "必须传参：\n" +
                    "1: customerId   (Integer)\n" +
                    "2: pageNum   (Integer)\n" +
                    "3: pageSize   (Integer)\n" +
                    "可选传参：\n" +
                    "1: orderNumber   (String) -- 默认值：\"\" ，即查询该顾客所有订单\n",
            response = Result.class,
            tags = {"查看订单"}
    )
    @GetMapping("/page")
    public Result<IPage<OrdersDTO>> findPage(@RequestParam Integer pageNum,
                                             @RequestParam Integer pageSize,
                                             @RequestParam Integer customerId,
                                             @RequestParam(defaultValue = "") String orderNumber) {
        IPage<Orders> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("customer_id",customerId);
        if (orderNumber != null && !orderNumber.trim().equals("")) {
            queryWrapper.eq("order_number", orderNumber.trim());
        }

        IPage<Orders> resultPage = ordersService.page(page, queryWrapper);

        // 将查询结果转换为 DTO 列表
        List<OrdersDTO> dtoList = resultPage.getRecords().stream().map(orders -> {
            return ordersService.convertOrdersEntityToOrdersDTO(orders);
        }).collect(Collectors.toList());

        // 创建新的 IPage 对象来封装 DTO 列表
        IPage<OrdersDTO> dtoPage = new Page<>(pageNum, pageSize, resultPage.getTotal());
        dtoPage.setRecords(dtoList);

        // Return the DTO page instead of the original resultPage
        return Result.success(dtoPage);
    }

    @ApiOperation(
            value = "订购饮料",
            notes = "判断余额是否足够、小料数量是否不多于3个、奶茶数量是否不多于2个的逻辑在移动端处理。\n" +
                    "只需传参：\n" +
                    "1: milkteaId   (Integer)\n" +
                    "2: customerId   (Integer)\n" +
                    "3: sugarLevel   (String)\n" +
                    "4: iceLevel   (String)\n" +
                    "5: toppingsIds   (List<Integer>)\n" +
                    "6: count   (Integer)\n",
            response = Result.class,
            tags = {"订购奶茶"}
    )
    @PostMapping    //格式在移动端处理
    public Result orderBeverages(@RequestBody OrdersDTO dto) {
        Orders orders = ordersService.convertOrdersDTOToOrdersEntity(dto);
        ordersService.saveOrUpdate(orders);
        ordersService.pay(orders);
        merchantHolderClient.presetPreparedOrders();
        return Result.success();
    }

    @GetMapping("/{orderId}")
    public Result<OrdersDTO> findOne(@PathVariable("orderId") Integer orderId){
        return Result.success(ordersService.convertOrdersEntityToOrdersDTO(ordersService.getById(orderId)));
    }

    @GetMapping("/orderNumber/{orderNumber}")
    public Result<OrdersDTO> findOneByOrderNumber(@PathVariable("orderNumber") String orderNumber){
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number",orderNumber.trim());
        Orders uniqueOrder = ordersService.getOne(queryWrapper);
        return Result.success(ordersService.convertOrdersEntityToOrdersDTO(uniqueOrder));
    }
}
